package com.itheima.service;

import com.itheima.entity.Role;
import com.itheima.entity.User;
import com.itheima.repository.RoleRepository;
import com.itheima.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class AdminService {

    @Autowired
    private UserRepository userRepository;
    @Autowired
    private RoleRepository roleRepository;

    // 获取所有用户
    public List<User> getAllUsers() {
        return userRepository.findAll();
    }

    // 修改用户状态（禁用/启用）
    // 修改用户角色的权限
    public String updateUserRolePermissions(String userName, Map<String, Boolean> newPermissions) {
        // 根据 userId 获取对应的用户角色
        Role role = roleRepository.findByUser_Username(userName); // 假设 RoleRepository 有一个根据 userId 查找 Role 的方法

        if (role != null) {
            // 更新角色的 permissions
            role.setPermissions(newPermissions);
            roleRepository.save(role);  // 保存角色更新后的信息
            return "User role permissions updated successfully";
        }
        return "Role not found for user";
    }

    // 重置用户密码
    public String resetUserPassword( String userName, String newPassword) {
        User user = userRepository.findByUsername(userName).orElse(null);
        if (user != null) {
            user.setPassword(newPassword);
            userRepository.save(user);
            return "Password reset successfully";
        }
        return "User not found";
    }

    public User getUserByName(String username) {
        return userRepository.findByUsername(username).get();
    }

    public String updateUserIsSuper(String userName) {
        User user = userRepository.findByUsername(userName).orElse(null);
        if(user.getUsername()=="admin") return "User don not update";
        if (user != null) {

            if(user.getIsSuper())user.setIsSuper(false);
            else user.setIsSuper(true);
            userRepository.save(user);
            return "User updated successfully";
        }
        return "User not found";
    }
}
